<?php
namespace app\modules\web\controllers;

use app\common\service\UploadService;
use app\modules\web\controllers\common\BaseController;

class UploadController extends BaseController
{
    public $allow_file_type = ["png","jpg","jpeg","gif"];
    //上传接口 bucket:avatar/brand/book
    public function actionPic()
    {
        $bucket =  trim( $this->post("bucket","") );
        $callback = "window.parent.upload";
        if( !$_FILES || !$_FILES['pic'] ){
            return "<script>{callback}.error('请选择文件之后再提交')</script>";
        }

        $file_name = $_FILES['pic']['name'];
        $tmo_file_extend = explode( ".",$file_name );

        if( !in_array( strtolower( end( $tmo_file_extend ) ),$this->allow_file_type )  ){
            return "<script>{$callback}.error('请上传指定类型的图片，图片类型为png,jpg,jpeg,gif')</script>";
        }
        //上传图片的业务逻辑
        $ret = UploadService::uploadByFile( $file_name,$_FILES['pic']['tmp_name'],$bucket );
        if( !$ret ){
            return "<script>{$callback}.error('".UploadService::getLastErrorMsg()."')</script>";
        }
        return "<script>{$callback}.success('{$ret['path']}')</script>";

    }
}